import axios, {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosRequestHeaders,
  AxiosResponse,
  AxiosError
} from 'axios'

import qs from 'qs'

import { config } from './config'
import { useCache } from '@/hooks/web/useCache'
import { resetRouter } from '@/router'

import { ElMessage } from 'element-plus'
import { useAppStore } from '@/store/modules/app'
import signMd5Utils from '@/utils/signMd5Utils'

import router from '@/router'

const { result_code, base_url, base_urlGateway, base_url_monitor } = config

export const PATH_URL = base_url[import.meta.env.VITE_API_BASEPATH]
export const GATEWAY = base_urlGateway[import.meta.env.VITE_API_BASEPATH]
export const MONITOR = base_url_monitor[import.meta.env.VITE_API_BASEPATH]
// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: PATH_URL, // api 的 base_url
  timeout: config.request_timeout // 请求超时时间
})

const { wsCache } = useCache()
const appStore = useAppStore()
// request拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (
      config.method === 'post' &&
      (config.headers as AxiosRequestHeaders)['Content-Type'] ===
        'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(config.data)
    }
    const token = appStore.token
    if (config.headers && typeof config.headers?.set === 'function') {
      config.headers.set('X-Sign', signMd5Utils.getSign(config.url, config.params || {}))
      config.headers.set('X-TIMESTAMP', signMd5Utils.getDateTimeToString())
      config.headers.set('x-access-token', token)
    }
    // ;(config.headers as AxiosRequestHeaders)['Token'] = 'test test'
    // get参数编码
    if (config.method === 'get' && config.params) {
      let url = config.url as string
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
    }
    if (config.method !== 'delete') {
      config.params = {
        _t: Math.trunc(new Date().getTime() / 1000),
        ...config.params
      }
    }
    return config
  },
  (error: AxiosError) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    } else if (response.config.headers['X-Sign']) {
      // 如果设置 x-Sign 跳过
      return response.data
    } else if (response.data.code === result_code || response.data.code === 0) {
      return response.data
    } else if (response.data.code == '401') {
      sessionStorage.clear()
      
    } else {
      ElMessage.error(response.data.message)
    }
  },
  (error: AxiosError) => {
    if (error?.response?.status === 401) {
      sessionStorage.clear()
      // 无需提示，跳转登录
      wsCache.clear()
      resetRouter() // 重置静态路由表
      appStore.setToken('')
      window.location.pathname = '/'
      return
    }
    console.log('err' + error) // for debug
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)
//**********************不同base_url************************************** */

// 创建axios实例
const serviceApi: AxiosInstance = axios.create({
  baseURL: GATEWAY, // api 的 base_url
  timeout: config.request_timeout // 请求超时时间
})
// request拦截器
serviceApi.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = appStore.token
    if (config.headers && typeof config.headers?.set === 'function') {
      config.headers.set('X-Sign', signMd5Utils.getSign(config.url, config.params || {}))
      config.headers.set('X-TIMESTAMP', signMd5Utils.getDateTimeToString())
      config.headers.set('x-access-token', token)
    }
    if (config.method !== 'delete') {
      config.params = {
        _t: Math.trunc(new Date().getTime() / 1000),
        ...config.params
      }
    }
    return config
  },
  (error: AxiosError) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)
// response 拦截器
serviceApi.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    } else if (response.config.headers['X-Sign']) {
      // 如果设置 x-Sign 跳过
      return response.data
    } else if (response.data.code === result_code || response.data.code === 0) {
      return response.data
    } else {
      ElMessage.error(response.data.message)
    }
  },
  (error: AxiosError) => {
    console.log('err' + error) // for debug
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)
//**********************不同base_url************************************** */

// 创建axios实例
const serviceApiMonitor: AxiosInstance = axios.create({
  baseURL: MONITOR, // api 的 base_url
  timeout: config.request_timeout // 请求超时时间
})
// request拦截器
serviceApiMonitor.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = appStore.token
    if (config.headers && typeof config.headers?.set === 'function') {
      // 统一去掉前缀 x-sign 需要
      config.headers.set('X-Sign', signMd5Utils.getSign(config.url, config.params || {}))
      config.headers.set('X-TIMESTAMP', signMd5Utils.getDateTimeToString())
      config.headers.set('x-access-token', token)
    }
    if (config.method !== 'delete') {
      config.params = {
        _t: Math.trunc(new Date().getTime() / 1000),
        ...config.params
      }
    }
    return config
  },
  (error: AxiosError) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)
// response 拦截器
serviceApiMonitor.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    } else if (response.config.headers['X-Sign']) {
      // 如果设置 x-Sign 跳过
      return response.data
    } else if (response.data.code === result_code || response.data.code === 0) {
      return response.data
    } else {
      ElMessage.error(response.data.message)
    }
  },
  (error: AxiosError) => {
    console.log('err' + error) // for debug
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)
export { service, serviceApi, serviceApiMonitor }
